<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"  %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<style>
	TH {font-size:12px;}
	TD {font-size:12px;}
</style>

<jsp:include page="../modal.jsp"/>
<div class="row">

	<div class="col-lg-12">
		
		<div id="alert_placeholder" style="display:none;"></div>
		
		<form id="searchform" name="searchform">
		<div class="panel panel-success">
			<div class="panel-heading">
				검색 조건
			</div>
			<div class="panel-body">
				<div class="row" >
					<div class="col-lg-2">
                		<div class="form-group">
		                	<div class="input-group">
		                		<span class="input-group-addon"><i class="fa fa-flag fa" style="width:15px;"></i></span>
	                            <select class="form-control" id="ord_fix_flag" name="ord_fix_flag">
							   		<option value="">전체</option>
	                               	<option value="N">미확정</option>
	                               	<option value="Y">확정</option>
	                            </select>
							</div>
						</div>
                	</div>
                	<div class="col-lg-2">
                		<div class="form-group">
	                		<div class="input-group">
	                			<span class="input-group-addon"><i class="fa fa-key fa" style="width:15px;"></i></span>
	                           	<input class="form-control"  id="ord_id" name="ord_id" placeholder="발주 아이디" />
							</div>
						</div>
                	</div>
                	<div class="col-lg-2">
                		<div class="form-group">
		                	<div class="input-group">
		                		<span class="input-group-addon"><i class="fa fa-tag fa" style="width:15px;"></i></span>
	                            <input class="form-control"  id="prd_name" name="prd_name" placeholder="상품명" />
							</div>
						</div>
                	</div>
                	<div class="col-lg-2">
                		<div class="form-group">
	                		<div class="input-group">
		                		<span class="input-group-addon"><i class="fa fa-building-o fa" style="width:15px;"></i></span>
		                		<input type="hidden" id="cus_id" name="cus_id" />
	                            <input class="form-control" id="cus_name" name="cus_name" data-provide="typeahead" placeholder="거래처"/>
							</div>
						</div>
                	</div>
                	
                	<div class="col-lg-2">
                		<div class="form-group">
                        	<input type="text" value="0" id="ord_quantity" name="ord_quantity">
                        </div>
                	</div>
                	
                </div>
                <div class="row">
                	<div class="col-lg-2">
                		<div style="margin-top:5px;text-align: center;">
	                		<label class="radio-inline">
								<input type="radio" name="ord_date_gbn" id="ord_date_gbn" value="P">예정일
					   		</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
					   		<label class="radio-inline">
	                            <input type="radio" name="ord_date_gbn" id="ord_date_gbn" value="R" checked="checked">확정일
	                        </label>
                		</div>
					</div>
	               	<div class="col-lg-5">
					   	<div class='input-group date'>
					   		<span class="input-group-addon">
					   			<i class="glyphicon glyphicon-calendar"></i>
							</span>
					   		<input type='text' class="form-control readonly" id="start_date" name="start_date" placeholder="시작일">
							<span class="input-group-addon" style="background-color: #fff;border:0px;">
							~
							</span>
					   		<input type='text' class="form-control readonly" id="end_date" name="end_date" placeholder="종료일">
					   	</div>
					</div>
					<div class="col-lg-3" style="text-align: left;margin-top:9px; font-size: 13px;">
	                	※ 거래처는 거래처명으로 자동 완성 기능 제공
					</div>
                	<div class="col-lg-2" style="text-align: right;">
                		<button type="reset" class="btn btn-default" onclick="$('#prd_customer').val(''); $('#prd_customer_name').attr('readonly', false);">비우기</button>
                		<button id="searchBtn" type="button" class="btn btn-warning" >검색</button>
                	</div>
                </div>
			</div>
		</div>
		</form>
				 <!-- <div class="table-responsive"> -->
				 <div class="dataTable_wrapper">
				 	<table class="table table-striped table-bordered table-hover" id="datatable_list">
				 		<thead>
                            <tr>
                                <th><i class="fa fa-flag fa" style="width:15px;"></i>확정</th>
                                <th><i class="fa fa-key fa" style="width:15px;"></i>아이디</th>
                                <th><i class="fa fa-tag fa" style="width:15px;"></i>상품명</th>
                                <th><i class="fa fa-building-o fa" style="width:15px;"></i>거래처</th>
                                <th>단가</th>
                                <th><i class="fa fa-plus-square fa" style="width:15px;"></i>수량</th>
                                <th>운송비</th>
                                <th>기타비</th>
                                <th>부가세</th>
                                <th>부가세 포함</th>
                                <th>총액</th>
                                <th>입고예정</th>
                                <th><i class="glyphicon glyphicon-calendar" style="width:15px;"></i>입고확정</th>
                            </tr>
                        </thead>
				 	</table>
				 </div>
			</div>
		</div>
	
<script>
	var oTable;
	
	$(document).ready(function() {
		
		$('#start_date').datepicker({
			autoclose: true,
		    format: "yyyy-mm-dd",
		    language: "kr",
		    todayHighlight: true,
		    toggleActive: true
		});
		
		$('#end_date').datepicker({
			autoclose: true,
		    format: "yyyy-mm-dd",
		    language: "kr",
		    todayHighlight: true,
		    toggleActive: true
		});
		
		$("input[name='ord_quantity']").TouchSpin({
            min: 0,
            max: 500,
            step: 1,
            decimals: 0,
            boostat: 5,
            maxboostedstep: 10,
            prefix: '<i class="fa fa-plus-square fa" style="width:15px;"></i>'
        });
		
		$('[data-toggle=confirmation]').confirmation();
		
		$('#cus_name').confirmation({
			title : '거래처를 변경하시겠습니까?'
			,trigger : 'manual'
			,btnOkLabel : '<i class="icon-ok-sign icon-white"></i> 예'
			,btnCancelLabel : '<i class="icon-remove-sign"></i> 아니오'
			,onConfirm : function(){
				$('#cus_name').attr("readonly", false);
				$('#cus_name').val("");
				$('#cus_id').val("");
				$('#cus_id_desc').html("* 거래처");
				$('#cus_name').confirmation('toggle');
			}
		});
		
		$('#cus_name').on('click', function() {
			
			if ($('#cus_name').attr("readonly")) {
				$('#cus_name').confirmation('toggle');
			} 
			
		});
		
		$('#cus_name').typeahead({
			minLength: 2
		   ,source: function (query, process) {
		        return $.ajax({
		            url: '/customer/searchCustomer.json',
		            type: 'post',
		            data: { keyword: query },
		            dataType: 'json',
		            success: function (result) {
		                var resultList = result.map(function (item) {
		                    var aItem = { id: item.ID, name: item.VALUE};
		                    return JSON.stringify(aItem);
		                });

		                return process(resultList);

		            }
		        });
		    } 

			,matcher: function (obj) {
		        var item = JSON.parse(obj);
		        return ~item.name.toLowerCase().indexOf(this.query.toLowerCase())
		    }

		    ,sorter: function (items) {          
		       var beginswith = [], caseSensitive = [], caseInsensitive = [], item;
		        while (aItem = items.shift()) {
		            var item = JSON.parse(aItem);
		            if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item));
		            else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item));
		            else caseInsensitive.push(JSON.stringify(item));
		        }

		        return beginswith.concat(caseSensitive, caseInsensitive)

		    }


		    ,highlighter: function (obj) {
		        var item = JSON.parse(obj);
		        var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
		        return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
		            return '<strong>' + match + '</strong>'
		        })
		    }

		   ,updater: function (obj) {
		        var item = JSON.parse(obj);
		        $('#cus_id').val(item.id);
		        $('#cus_name').attr('readonly', true);
		        return item.name;
		    }
		});
		
		oTable = $('#datatable_list').dataTable({
			columnDefs:[
	
	            {data: "ORD_FIX_FLAG", 			visible:true,	targets:0  },
	            {data: "ORD_ID", 				visible:true,	targets:1  },
	            {data: "PRD_NAME", 				visible:true,	targets:2  },
	            {data: "CUS_NAME", 				visible:true,	targets:3  },
	            {data: "ORD_UNIT_PRICE", 		visible:true,	targets:4  },
	            {data: "ORD_QUANTITY", 			visible:true,	targets:5  },
	            {data: "ORD_DELIVERY_PRICE", 	visible:true,	targets:6  },
	            {data: "ORD_ETC_PRICE", 		visible:true,	targets:7  },
	            {data: "ORD_TAX_PRICE",			visible:true,	targets:8  },
	            {data: "ORD_TAX_FLAG",			visible:false,	targets:9  },
	            {data: "ORD_VALUE_PRICE",		visible:true,	targets:10  },
	            {data: "ORD_PLAN_DATE", 		visible:true,	targets:11  },
	            {data: "ORD_REAL_DATE", 		visible:true,	defaultContent:"미입력",	 targets:12 }
	        ],
			bServerSide: true,
	    	bProcessing: true,
	    	bDeferRender: true,
	    	bAutoWidth: false,
	    	bRetrieve: true,
	    	bFilter: false,
	    	bInfo: true,
	    	searching: false,
	    	//stateSave: true,
	    	lengthMenu: [10, 15, 20, 25, 30, 35, 40, 45, 50, 100],
	    	pagingType: "full_numbers",
	    	aaSorting: [[ 1, "desc" ]],
	    	language: {
	            emptyTable: "<spring:message code='brd.no.record' />",
	            info: "Total Record : _MAX_"
	        },
	        sAjaxSource: "/order/listData.json",
	        fnServerParams: function(aoData) {
	            var serializedForm = $('#searchform').serializeArray();
	            for (var n in serializedForm) {
	               var tmpobj = serializedForm[n];
	               var key = tmpobj['name'];
	               var value = tmpobj['value'];
	               aoData.push({"name":key,"value":value});
	            }
	        },
	        fnServerData: function ( sSource, aoData, fnCallback, oSettings ) {
	            oSettings.jqXHR = $.ajax( {
	              dataType: 'json',
	              type: "GET",
	              url: sSource,
	              data: aoData,
	              success: fnCallback,
	              error: function (e) {
	            	  bs_alert.modal("<spring:message code='comm.session.expire' />", "info","LOGOUT");
	              }
	            });
	        },
	    	fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
	    		$('td:eq(4)', nRow).css('text-align', 'right');
	    		$('td:eq(4)', nRow).html('<i class="fa fa-won fa" style="width:15px;"></i>&nbsp;' + commaValue(aData.ORD_UNIT_PRICE));
	    	
	    		$('td:eq(5)', nRow).css('text-align', 'right');
	    		
	    		$('td:eq(6)', nRow).css('text-align', 'right');
	    		$('td:eq(6)', nRow).html('<i class="fa fa-won fa" style="width:15px;"></i>&nbsp;' + commaValue(aData.ORD_DELIVERY_PRICE));
	    		
	    		$('td:eq(7)', nRow).css('text-align', 'right');
	    		$('td:eq(7)', nRow).html('<i class="fa fa-won fa" style="width:15px;"></i>&nbsp;' + commaValue(aData.ORD_ETC_PRICE));
	    		
	    		$('td:eq(8)', nRow).css('text-align', 'right');
	    		$('td:eq(8)', nRow).html('<i class="fa fa-won fa" style="width:15px;"></i>&nbsp;' + commaValue(aData.ORD_TAX_PRICE));
	    		
		    	$('td:eq(9)', nRow).css('text-align', 'right');
	    		
	    		if (aData.ORD_TAX_FLAG == 'Y') {
		    		$('td:eq(9)', nRow).html('<i class="fa fa-won fa" style="width:15px;"></i>&nbsp;' + commaValue(aData.ORD_VALUE_PRICE) + " (포)");
	    		} else {
	    			$('td:eq(9)', nRow).html('<i class="fa fa-won fa" style="width:15px;"></i>&nbsp;' + commaValue(aData.ORD_VALUE_PRICE) + " (미)");
	    		}
	    		
	    		
	    		$('td:eq(0)', nRow).css('text-align', 'center');
	    		
	    		if (aData.ORD_FIX_FLAG == 'Y') {
	    			$('td:eq(0)', nRow).html('확정');
	    		} else {
	    			$('td:eq(0)', nRow).html('미확정');
	    		}
	    		
	    	}
	        ,oTableTools: {
	            sRowSelect: "single",
	            aButtons: [ 
								/* { sExtends :'select_all' , 	sButtonText:'전체 선택' },
								{ sExtends :'select_none' , sButtonText:'전체 해제' }, */
								{ sExtends :'xls' , 		sButtonText:'엑셀 다운로드', 		sFileName: '*.xls' },
								{ sExtends :'copy' , 		sButtonText:'복사' }
	        				],
	            fnRowSelected: function(node){
	            	
	            	// SESSION 여부 확인
	            	if (!isSession()) {
	            		bs_alert.modal("<spring:message code='comm.session.expire' />", "info","LOGOUT");
	            		return;
	            	}

	            	var s = $(node).children();
	            	
	            	$.ajax( {
	  	              	dataType: 'html',
	  	              	type: "POST",
	  	              	url: "/order/modifyForm.ur",
	  	              	data: {
	  	            	  		prd_id: $(s[0]).text()
	  	            	  		,layout: 'N'
	  	              	},
						success: function(data) {
							
							$('#doc-modal-dialog').css('width', '70%');
							$('#doc-modal-body').html(data);
							$('#doc-modal-title').html($('#modal-title').html());
							$('#doc-modal').modal('toggle');
							
						},
						error: function(xhr, status, err) {
							alert(err);
	  	             	}
	  	            });
	            	
	             	
	            }
	        }
	    	,dom: '<"top"<"row"<"col-lg-6 text-left"T><"col-lg-6 text-right"l>>>rt<"bottom"<"row"<"col-lg-2 text-left"i><"col-lg-10 text-right"p>>>'
		});
	
	   	$('.form-control').keypress(function (e) {
			if (e.which == 13) {
				$('#searchBtn').trigger("click");
			}
	   	});
	    
		$('#searchBtn').click(function() {
					
			oTable.fnReloadAjax();
			
	    });
		
	});
	

</script>
